#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'xuwenjie'

"""
 1、找到工程 并打包生成ipa文件
 2、ipa文件上传
 3、发送邮件给测试人员

 自动化打包方式
 xcodebuild + xcrun(不推荐)
 arhive+exportArchive

  """

import os
import getpass
import requests
import smtplib
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.header import Header

# 蒲公英相关参数设置
PGY_URL = "http://www.pgyer.com/apiv1/app/upload"
# 蒲公英账户下的用户key
PGY_UKey = "7e613f06d4f54a6512cc36c2a952228e"
# 蒲公英账户下的接口key
PGY_APIKey = "a28e30525be0294c569e443641f8dd99"
# 应用安装密码 (选填)
PGY_PW = ""
# 应用安装方式 值为(1,2,3)。1：公开，2：密码安装，3：邀请安装。默认为1公开
PGY_INSTALL_type = 1
# 应用更新描述信息
PGY_DES = "1月28日 动画绘本馆2.1.0同学圈一期+听书优化需求+任务模块 正式服"
#项目参数相关设置
isWorkSpace = True

# 开发版本
isDev = True


#项目的相关配置
mainPath = "/Users/wenjiexu/Desktop/EllaFamily"
# 项目的名称 类似xxxxx.xcodeproj
targetName = "EllaFamily"
# 证书名 Automatic 模式下不需要
certificateName = "DianDu Technology Co., Ltd."
# 生成的解压缩文件路径
archivePath = "/Users/wenjiexu/EllaFamily/xcode"
# ipa路径
ipaPath = "%s/%s/%s.ipa" % (archivePath, targetName, targetName)


# 开发者网站参数
DeveloperAccountName = "diandu100@sina.com"
DeveloperAccountPWD = "Hzsunflowers13579"

# 邮件的相关参数设置
MAIL_HOST = "smtp.ellabook.cn"
# //邮件标题
MAIL_SUBJECT = "动画绘本馆2.1.0同学圈一期+听书优化需求+任务模块"
# //收件人
MAIL_TO = "gehangping@ellabook.cn"
# //发件人MAIL_
MAIL_FROM = "xuwenjie@ellabook.cn"
# 邮箱密码
Mail_PassWord = "Diandu100"

ReceiveMails = ["gehangping@ellabook.cn", "tukezuan@ellabook.cn", "wujietao@ellabook.cn", "zhangshuying@ellabook.cn", "jianingru@ellabook.cn", "zhangchi@ellabook.cn", "wangjin1@ellabook.cn", "yuanjunru@ellabook.cn", "caizhe@ellabook.cn"]


class IPAHelper(object):
    def __init__(self):
        print("工具初始化")

        # clean工程

    def cleanProject(self):
        global isWorkSpace
        if isWorkSpace:
            os.system(
                'cd %s;xcodebuild -workspace %s.xcworkspace -scheme %s clean' % (mainPath, targetName, targetName))
        else:
            os.system('cd %s;xcodebuild -target %s clean' % (mainPath, targetName))
        return



    def buildProject(self):

        if isWorkSpace:
            os.system(
                "cd %s;xcodebuild -workspace %s.xcworkspace -scheme %s -configuration Release  -archivePath %s/%s.xcarchive clean archive" % (
                    mainPath, targetName, targetName, archivePath, targetName))
        else:
            os.system(
                "cd %s;xcodebuild -project %s.xcodeproj -scheme %s -configuration Release  -archivePath %s/%s.xcarchive clean archive" % (
                    mainPath, targetName, targetName, archivePath, targetName))
        return


    def cerateIPA(self):
        if isDev:
            os.system(
                "cd %s; xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s/%s -exportOptionsPlist %s/DevExportOptions.plist -allowProvisioningUpdates -quiet" % (
                    mainPath, archivePath, targetName, archivePath, targetName, archivePath))
        else:
            os.system(
                "cd %s; xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s/%s -exportOptionsPlist %s/DisExportOptions.plist -allowProvisioningUpdates -quiet" % (
                    mainPath, archivePath, targetName, archivePath, targetName, archivePath))
        return

    def uploadToPGY(self):
        print("上传到蒲公英")
        path = "%s/%s/%s.ipa" % (archivePath, targetName, targetName)
        f_op = open(path, 'rb')
        print(path)
        print(f_op.readlines())

        if os.path.exists(path):
            print("找到ipa文件")
            # 请求参数字典
            params = {
                'uKey': PGY_UKey,
                '_api_key': PGY_APIKey,
                # 'file': f_op,
                'installType': PGY_INSTALL_type,
                'password': PGY_PW,
                'updateDescription': PGY_DES
            }

            response = requests.post(PGY_URL, files={"file": open(path, 'rb')}, data=params)

            if str(response.json()["code"]) == "0":
                self.sendMail(response.json()["data"])    #发送邮件给测试人员

            print(response.text)
            print(response.headers)
        else:
            print("没有找到ipa文件")

    def uploadToItunesConnect(self):
        print("上传到ItunesConnect")
        altoolPath = "/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool"
        validateresult = os.popen("%s --validate-app -f %s/ -u %s -p %s -t ios --output-format xml" % (
        altoolPath, ipaPath, DeveloperAccountName, DeveloperAccountPWD)).read()
        uploadresult = os.popen("%s --upload-app -f %s -u %s -p %s -t ios --output-format xml" % (
        altoolPath, ipaPath, DeveloperAccountName, DeveloperAccountPWD)).read()

        print(str(uploadresult))

        if ("success-message" in str(uploadresult)):
            print("上传成功")
        elif ("product-errors" in str(uploadresult)):
            print("上传失败 %s", uploadresult)
        else:
            print("未知失败原因")

        return
        # self.sendMail({"appName": targetName,
        #                "appVersion": "appVersion",
        #                "appShortcutUrl": "暂无",
        #                "appUpdated": "暂无"
        #                })

    def _format_addr(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    def sendMail(self, responseResult):
        print("发送邮件")

        # if not os.path.exists("%s/%s.ipa/%s.ipa" % (archivePath, targetName, targetName)):
        #     print("发送邮件 没有找到ipa文件")
        #     return
        # =============msginfo格式===============
        # < html >
        # < body >
        # < table >
        # < tr >
        # < th > 应用名称 < / th >
        # < th > % s < / th >
        # < / tr >
        # < tr >
        # < th > 应用版本 < / th >
        # < th > % s < / th >
        # < / tr >
        # < tr >
        # < th > 应用地址 < / th >
        # < th > https: // www.pgyer.com / % s < / th >
        # < / tr >
        # < tr >
        # < th > 应用更新时间 < / th >
        # < th > % s < / th >
        # < / tr >
        # < / table >
        # < img
        # src = % s
        # width =\"150\" height=\"150\">
        # < / body >
        # < / html >

        msgInfo = "<html><body><table><tr><th>应用名称</th><th>%s</th></tr><tr><th>应用版本</th><th>%s</th></tr><tr><th>应用地址</th><th>https://www.pgyer.com/%s</th></tr><tr><th>应用更新时间</th><th>%s</th></tr></table>< img src=%s width=\"150\" height=\"150\"></body></html>" % (
            responseResult["appName"], str(responseResult["appVersion"]), str(responseResult["appShortcutUrl"]),
            str(responseResult["appUpdated"]), str(responseResult["appQRCodeURL"]))
        print(msgInfo)
        msg = MIMEText(msgInfo, 'html', 'utf-8')
        msg["Subject"] = MAIL_SUBJECT
        msg['From'] = self._format_addr('客户端 <%s>' % MAIL_FROM)
        msg['To'] = ",".join(ReceiveMails)
        try:
            # 创建一个SMTP对象
            server = smtplib.SMTP()
            print(server)
            # 通过connect方法链接到smtp主机
            server.connect(MAIL_HOST, "25")
            server.set_debuglevel(1)
            # 启动安全传输模式
            # server.starttls()
            # 登录邮箱
            # 校验用户，密码
            server.login(MAIL_FROM, Mail_PassWord)
            # 发送邮件
            server.sendmail(MAIL_FROM, ReceiveMails, msg.as_string())
            server.quit()
            # 发送成功并打印
            print("邮件发送成功 \n发送人:%s\n发送内容:\n%s接收者:%s " % (MAIL_FROM, msg, ReceiveMails))

        except Exception as e:
            print("邮件发送失败：" + str(e))


if __name__ == '__main__':
    helper = IPAHelper()

    #clean工程
    helper.cleanProject()
    #build app
    helper.buildProject()
    #生成ipa
    helper.cerateIPA()

    if isDev:
        # 上传到蒲公英
        helper.uploadToPGY()
    else:
        # 上传到itunes
        helper.uploadToItunesConnect()
